package com.pms.web;
import com.pms.entity.AdverAgency;
import com.pms.entity.AdverPlace;
import com.pms.exception.R;
import com.pms.service.IAdverAgencyService;
import com.pms.service.IAdverPlaceService;
import com.pms.util.OSSClientUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.pms.controller.BaseController;
import com.pms.service.IAdverDetailsService;
import com.pms.entity.AdverDetails;
import org.springframework.web.bind.annotation.RequestMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 广告信息资源表
 * 20171120
 */
@RestController
@RequestMapping("adverDetails")
@Api(value = "后台广告信息",description = "后台广告信息")
public class AdverDetailsController extends BaseController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    IAdverDetailsService adverDetailsService;
    @Autowired
    IAdverAgencyService adverAgencyService;
    @Autowired
    IAdverPlaceService adverPlaceService;


    /**
     * 分页查询广告信息
     * @param limit
     * @param page
     * @param adverName
     * @return
     */
    @ApiOperation(value = "分页查询广告信息")
    @RequestMapping(value = "/page",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="limit",value="条数",required = false,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="page",value="页数",required = false,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="adverName",value="广告名称",required = false,dataType = "String",paramType="form")
    })
    public R page(Integer limit, Integer page, String adverName){
        if(limit==null){limit=10;}
        if(page==null){page=1;}
        Page<AdverDetails> pages = new Page<AdverDetails>(page,limit);
        pages = adverDetailsService.selectPage(pages,new EntityWrapper<AdverDetails>().like("adver_name",adverName));
        return R.ok().put("data",pages).putDescription(AdverDetails.class);
    }

    /**
     * 删除广告信息
     * @param adverId
     * @return
     */
    @ApiOperation(value = "删除广告信息")
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    @ApiImplicitParams({
             @ApiImplicitParam(name="adverId",value="广告信息ID",required = true,dataType = "Long",paramType="form")
    })
    public R delete(Long adverId){
        parameterIsNull(adverId,"广告ID不能为空");
        AdverDetails   adver=adverDetailsService.selectById(adverId);
        parameterIsNull(adver,"该广告信息不存在");
      List<AdverAgency> adverAgency =adverAgencyService.selectList(new EntityWrapper<AdverAgency>().eq("adver_id",adver.getAdverId()));
       if (adverAgency.size()>0){
           for (AdverAgency ac:adverAgency){
               adverAgencyService.delete(new EntityWrapper<AdverAgency>().eq("adver_id",ac.getAdverId()));
           }
       }
        OSSClientUtil.deleteOldimgUrl(adver.getAdverUrl());//删除阿里云图片
        adverDetailsService.deleteById(adverId);
    return  R.ok();
    }



    /**
     * 查询广告信息
     * @param adverId
     * @return
     */
    @ApiOperation(value = "查询广告信息")
    @RequestMapping(value = "/queryById",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="adverId",value="广告信息ID",required = true,dataType = "Long",paramType="form")
    })
    public R queryById(Long adverId){
        parameterIsNull(adverId,"广告ID不能为空");
        AdverDetails   adver=adverDetailsService.queryById(adverId);
        parameterIsNull(adver,"该广告信息不存在");
        return  R.ok().put("data",adver).putDescription(AdverDetails.class);
    }

    /**
     * 添加询广告信息
     * @param adverName
     * @param startTime
     * @param endTime
     * @param placeId
     * @param adverUrl
     * @param contentType
     * @param adverValue
     * @param adverKeyId
     * @param agencyId
     * @param agencys
     * @return
     */
    @ApiOperation(value = "添加询广告信息")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="adverName",value="广告名称",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="startTime",value="开始时间",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="endTime",value="结束时间",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="placeId",value="位置ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="adverUrl",value="广告路径",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="contentType",value="1 商品 ，2 内连接  3外链接4.分类",required = true,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="adverValue",value="广告所服务对象名称",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="adverKeyId",value="广告所服务的对象id",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="agencyId",value="机构ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="agencys",value="多个机构ID（用，隔开）",required = true,dataType = "String",paramType="form"),
    })
    public R add(String adverName,String startTime,String endTime,Long placeId,String adverUrl,Integer contentType,String adverValue,Long adverKeyId,Long agencyId,String agencys){
        parameterIsBlank(adverName,"广告名称不能为空");
        parameterIsBlank(startTime,"开始时间不能为空");
        parameterIsBlank(endTime,"结束时间不能为空");
        parameterIsBlank(adverUrl,"广告路径不能为空");
        parameterIsNull(placeId,"广告位置ID不能为空");
        parameterIsNull(contentType,"广告连接类型不能为空");
        parameterIsNull(adverKeyId,"广告所服务的对象id不能为空");
        parameterIsNull(agencyId,"机构ID不能为空");//获取当前对象的机构ID
        AdverDetails adverDetails=new AdverDetails();
        adverDetails.setAdverName(adverName);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date stratTime1= null;
        Date endTime1 =null;
        try {
            stratTime1 = sdf.parse(startTime);
            endTime1=sdf.parse(endTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (endTime1.getTime() <= stratTime1.getTime()){
            return  R.error("结束时间必须要大于开始时间");
        }
        adverDetails.setStartTime(stratTime1);
        adverDetails.setEndTime(endTime1);
        adverDetails.setClickCount(0);//点击量
        AdverPlace place=  adverPlaceService.selectById(placeId);
        parameterIsNull(place,"该广告位置信息不存在");
        adverDetails.setPlaceId(placeId);
        adverDetails.setClientType(1);
        adverDetails.setContentType(contentType);
        adverDetails.setAdverUrl(adverUrl);
 //    adverDetails.setAgencyId();//当前机构ID
        if (contentType==1){//商品
//            ProCommodity proCommodity=proCommodityService.selectById(adverKeyId);
//            parameterIsNull(proCommodity,"该商品信息不存在");
//            adverDetails.setAdverKeyId(proCommodity.getCommodityId().toString());//商品ID
//            adverDetails.setAdverValue(proCommodity.getCommodityName());//商品名称
        }else if (contentType==4){//分类
//            ProCommodity proCommodity=proCommodityService.selectById(adverKeyId);
//            parameterIsNull(proCommodity,"该商品信息不存在");
//            adverDetails.setAdverKeyId(proCommodity.getCommodityId().toString());//商品ID
//            adverDetails.setAdverValue(proCommodity.getCommodityName());//商品名称
        }else{//网址连接
            adverDetails.setAdverKeyId(adverKeyId);
        }
        List<AdverAgency> AdverAgencyList = new ArrayList<AdverAgency>();
        if (!StringUtils.isEmpty(agencys)){
            String[] Agencys =agencys.split(",");
            for(String agencyIds : Agencys){
                AdverAgency aa=new AdverAgency();
                aa.setAdverId(adverDetails.getAdverId());
                aa.setAgencyId(Long.parseLong(agencyIds));
                aa.setCreateTime(new Date());
                aa.setCreateBy(Long.parseLong(agencyIds));
                AdverAgencyList.add(aa);
            }
        }
        adverDetailsService.insert(adverDetails);
        adverAgencyService.insertBatch(AdverAgencyList);
        return  R.ok();
    }

    /**
     * 修改广告信息
     * @param adverId
     * @param adverName
     * @param startTime
     * @param endTime
     * @param placeId
     * @param adverUrl
     * @param contentType
     * @param adverValue
     * @param adverKeyId
     * @param agencyId
     * @param agencys
     * @return
     */
    @ApiOperation(value = "修改广告信息")
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="adverId",value="广告信息ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="adverName",value="广告名称",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="startTime",value="开始时间",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="endTime",value="结束时间",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="placeId",value="位置ID",required = false,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="adverUrl",value="广告路径",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="contentType",value="1 商品 ，2 内连接  3外链接4.分类",required = false,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="adverValue",value="广告所服务对象名称",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="adverKeyId",value="广告所服务的对象id",required = false,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="agencyId",value="机构ID",required = false,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="agencys",value="多个机构ID（用，隔开）",required = false,dataType = "String",paramType="form"),
    })
    public R update(Long adverId,String adverName,String startTime,String endTime,Long placeId,String adverUrl,Integer contentType,String adverValue,Long adverKeyId,Long agencyId,String agencys) {
        parameterIsNull(adverId,"广告信息ID不能为空");
        AdverDetails adver=adverDetailsService.selectById(adverId);
        parameterIsNull(adver,"该广告信息不存在");
        if (StringUtils.isNotBlank(adverName)){
            adver.setAdverName(adverName);
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date stratTime1= null;
        Date endTime1 =null;
        if (StringUtils.isNotBlank(startTime)){
            try {
                stratTime1=sdf.parse(startTime);
                if (StringUtils.isNotBlank(endTime)){
                    endTime1=sdf.parse(endTime);
                    if (endTime1.getTime() <= stratTime1.getTime()){
                        return  R.error("结束时间必须要大于开始时间");
                    }
                    adver.setEndTime(endTime1);
                }
                adver.setStartTime(stratTime1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (placeId!=null){
            AdverPlace place=  adverPlaceService.selectById(placeId);
            parameterIsNull(place,"该广告位置信息不存在");
            adver.setPlaceId(placeId);
        }
        if (StringUtils.isNotBlank(adverUrl)){
            adver.setAdverUrl(adverUrl);
        }
        if (contentType != null){
            adver.setContentType(contentType);
            if (contentType==1){//商品
    //            ProCommodity proCommodity=proCommodityService.selectById(adverKeyId);
    //            parameterIsNull(proCommodity,"该商品信息不存在");
    //            adverDetails.setAdverKeyId(proCommodity.getCommodityId().toString());//商品ID
    //            adverDetails.setAdverValue(proCommodity.getCommodityName());//商品名称
            }else if (contentType==4){//分类
    //            ProCommodity proCommodity=proCommodityService.selectById(adverKeyId);
    //            parameterIsNull(proCommodity,"该商品信息不存在");
    //            adverDetails.setAdverKeyId(proCommodity.getCommodityId().toString());//商品ID
    //            adverDetails.setAdverValue(proCommodity.getCommodityName());//商品名称
            }else{//网址连接
                adver.setAdverKeyId(adverKeyId);
                }
            }
        if (StringUtils.isNotBlank(agencys)){
            List<AdverAgency> AdverAgencyList = new ArrayList<AdverAgency>();
                String[] Agencys =agencys.split(",");
                for(String agencyIds : Agencys){
                    adverAgencyService.delete(new EntityWrapper<AdverAgency>().eq("adver_id",adver.getAdverId()));
                    AdverAgency aa=new AdverAgency();
                    aa.setAdverId(adver.getAdverId());
                    aa.setAgencyId(Long.parseLong(agencyIds));
                    aa.setCreateTime(new Date());
                    aa.setCreateBy(Long.parseLong(agencyIds));
                    AdverAgencyList.add(aa);
                }
            adverAgencyService.insertBatch(AdverAgencyList);
        }
        adverDetailsService.updateAllColumnById(adver);
        return  R.ok();
    }


}